package com.boot.token;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.boot.entity.SysToken;
import com.boot.mapper.SysTokenMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysPersistentTokenRepositoryImpl implements PersistentTokenRepository {
    @Autowired
    SysTokenMapper sysTokenMapper;

    @Override
    public void createNewToken(PersistentRememberMeToken token) {
        SysToken sysToken = new SysToken();
        sysToken.setUsername(token.getUsername());
        sysToken.setSeries(token.getSeries());
        sysToken.setTokenValue(token.getTokenValue());
        sysToken.setDate(token.getDate());
        sysTokenMapper.insert(sysToken);

    }

    @Override
    public void updateToken(String series, String tokenValue, Date lastUsed) {
        UpdateWrapper<SysToken> updateWrapper = Wrappers.<SysToken>update().eq("series", series).set("token", tokenValue).set("last_used", lastUsed);
        sysTokenMapper.update(null, updateWrapper);
    }

    @Override
    public PersistentRememberMeToken getTokenForSeries(String seriesId) {
        SysToken sysToken = sysTokenMapper.selectOne(Wrappers.<SysToken>query().eq("series", seriesId));
        return sysToken != null ? new PersistentRememberMeToken(sysToken.getUsername(), sysToken.getSeries(), sysToken.getTokenValue(), sysToken.getDate()) : null;
    }

    @Override
    public void removeUserTokens(String username) {
        sysTokenMapper.delete(Wrappers.<SysToken>query().eq("username", username));
    }
}
